/**
 * 1. 提供授权窗口
 */

const path = require('path');
const express = require('express');
const uuid = require('uuid');
const app = express();
// const ejs = require('ejs');

app.set('views', path.join(__dirname, './views'));
app.set('view engine', 'ejs');

/**
 * 写一个中间键，模拟用户已经登录
 */
app.use((req, res, next) => {
  req.loginUserId = 'tom';
  next();
});

const appInfo = {
  appId: '1one2two', // oauth 生成的应用ID
  secret: '111111', // oauth 生成的应用秘钥
  name: 'tom’s home',
  desc: 'tom 的个人网站',
};

app.get('/authorize', (req, res) => {
  res.render('auth', {
    loginUserId: req.loginUserId,
    appInfo,
  });
});

const codes = {};
const tokens = {};
// 点击到登录
// http://localhost:3000/authorize?clientId=1one2two&redirectUri=http://localhost:3001/callback
app.post('/authorize', (req, res) => {
  const code = uuid.v4();
  const clientId = req.query.clientId;
  codes[code] = {
    clientId,
    userId: req.loginUserId,
  };
  const redirectUri = req.query.redirectUri + `&code=${code}`;
  res.redirect(redirectUri);
});

app.get('/token', (req, res) => {
  const code = req.query.code;
  const token = uuid.v4();
  tokens[token] = {
    ...codes[code],
  };
  res.send({
    code: 200,
    token,
  });
});

console.log('server is running:3000...');
app.listen(3000);
